<?php
namespace app\manage\controller;

use think\Controller;
use think\Db;
use think\Route;
use app\common\lib\ManageAuth;

class Base extends Controller
{

	public function _initialize(){

        header('Access-Control-Allow-Origin: *');
        header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
        header('Access-Control-Allow-Methods: GET, POST, PUT');
        // 登录验证

		if(is_null(session('admin'))){
           $this->redirect('index/logpage');
        }

        $admin = session('admin');
        define('UID',session('admin.id'));

        // 权限验证
		$module = $this->request->module();
        $controller = $this->request->controller();
        $rule = $module.'/'.$controller;
        $ManageAuth = new ManageAuth;
        if(false===$ManageAuth->checkGroupId($admin['group_id'],$rule)){
            $this->error('权限不足');
        }

        // 设置初始前台用户
        $memberModel = new \app\common\model\Member;
        if(!$memberModel->count()){
            // 如果没用用户，则设置初始会员
            $this->redirect('init/index');
        }

        $this->assign('token',self::genToken());
	}

    /**
     * 生成token
     */
    public static function genToken() {
        $token_cookie_name = 'JS_TOKENCOOKIE_' . md5('wxmax'. session('admin.id'));
        if (isset($_COOKIE[$token_cookie_name])) {
            return $_COOKIE[$token_cookie_name];
        } else {
            $token = md5(getRandStr(16));
            setcookie($token_cookie_name, $token, 0, '/');
            return $token;
        }
    }

    /**
     * 检查token
     */
    public static function checkToken(){
        $token = isset($_REQUEST['token']) ? addslashes($_REQUEST['token']) : '';
        if ($token != self::genToken()) {
            return false;
        }
        return true;
    }

}

